package com.pioneer.swing.model;

import com.pioneer.dao.*;
import com.pioneer.beans.*;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
import java.util.List;
import java.util.Iterator;

/**
 * Title:        Pioneer Metals Application
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Pioneer Metals
 * @author Gary Chen
 * @version 1.0
 */

public class AdminItemEntryTable extends DefaultTableModel {

	private JobDAO jobDAO;
	private String quoteNum;

	// column numbers
	public static final int ITEM_NUM=0;
	public static final int ITEM_QTY=1;
	public static final int ITEM_PRICE=2;
	public static final int ITEM_DESC=3;
	public static final int ITEM_COST=4;
	public static final int ITEM_SALE_TOTAL=5;
	public static final int ITEM_COST_TOTAL=6;
	public static final int ITEM_MARGIN=7;

    public AdminItemEntryTable(JobDAO jobDAO,Key key) {
		JobKey jobKey=(JobKey)key;
		String quoteNum = null;
		if (jobKey.getQuoteNums()!=null) {
			quoteNum=jobKey.getQuoteNums()[0];
		}
		columnIdentifiers=new Vector();
		columnIdentifiers.add(TableConstants.ITEM_NUM);
		columnIdentifiers.add(TableConstants.ITEM_QTY);
		columnIdentifiers.add(TableConstants.ITEM_PRICE);
		columnIdentifiers.add(TableConstants.ITEM_DESC);
		columnIdentifiers.add(TableConstants.ITEM_COST);
		columnIdentifiers.add(TableConstants.ITEM_SALE_TOTAL);
		columnIdentifiers.add(TableConstants.ITEM_COST_TOTAL);
		columnIdentifiers.add(TableConstants.ITEM_MARGIN);

		this.jobDAO=jobDAO;
		this.quoteNum=quoteNum;
		if (quoteNum!=null) refresh();
    }

	public void setValueAt(Object aValue,
                       int row,
                       int column) {
			if (column==ITEM_QTY) {
				try {
					aValue = new Integer(aValue.toString());
				}
				catch (NumberFormatException ex) {
					aValue = new Integer(0);
				}
			}
			if ((column==ITEM_PRICE) || (column==ITEM_COST) || (column==ITEM_SALE_TOTAL) || (column==ITEM_COST_TOTAL) || (column==ITEM_MARGIN)){
				try {				
					aValue = new Double(aValue.toString());
					}
				catch (NumberFormatException ex) {
					aValue = new Double(0);
				}
			}
			super.setValueAt(aValue,row,column);
			switch(column) {
			case ITEM_NUM:
				fillInfo(aValue.toString(),row);
				break;
			case ITEM_QTY:
				doPriceCalc(row);
				doCostCalc(row);
				doMargin(row);
				break;
			case ITEM_PRICE:
				doPriceCalc(row);
				doMargin(row);
				break;
			}
			
	}
	
	private void fillInfo(String itemNum,int row) {
		Item item =null;
		try {
			item = jobDAO.getItem(itemNum);
		}
		catch (DataAccessException ex) {
			System.err.println("Couldn't fill in item table: "+ex.getMessage());
		}
		if (item!=null) {
			setValueAt(item.getDescription(),row,ITEM_DESC);
			setValueAt(new Double(item.getPrice()),row,ITEM_PRICE);
			setValueAt(new Double(item.getCost()),row,ITEM_COST);			
		}
	}

	private void doPriceCalc(int row) {
		Object qtyObj = getValueAt(row,ITEM_QTY);
		Object priceObj = getValueAt(row,ITEM_PRICE);
		if ((qtyObj!=null) && (priceObj!=null)){
			try {
				double result=((Integer)qtyObj).intValue()*((Double)priceObj).doubleValue();
				setValueAt(new Double(rounder(result)),row,ITEM_SALE_TOTAL);
			}
			catch (Exception ex) {
				setValueAt(new Double(0),row,ITEM_SALE_TOTAL);
			}
		}		
	}
	
	private void doCostCalc(int row) {
		Object qtyObj = getValueAt(row,ITEM_QTY);
		Object costObj = getValueAt(row,ITEM_COST);
		if ((qtyObj!=null) && (costObj!=null)){
			try {
				double result=((Integer)qtyObj).intValue()*((Double)costObj).doubleValue();
				setValueAt(new Double(rounder(result)),row,ITEM_COST_TOTAL);
			}
			catch (Exception ex) {
				setValueAt(new Double(0),row,ITEM_COST_TOTAL);
			}
		}
	}
	
	private void doMargin(int row) {
		Object saleObj = getValueAt(row,ITEM_SALE_TOTAL);
		Object costObj = getValueAt(row,ITEM_COST_TOTAL);
		if ((saleObj!=null) && (costObj!=null)){
			try {
				double result=(((Double)saleObj).doubleValue()-((Double)costObj).doubleValue())/((Double)saleObj).doubleValue()*100;
				setValueAt(new Double(rounder(result)),row,ITEM_MARGIN);
			}
			catch (Exception ex) {
				setValueAt(new Double(0),row,ITEM_MARGIN);
			}
		}
	}

	public Object getValueAt(int row, int column) {
		Object objFound=super.getValueAt(row,column);
		if (objFound==null) {
			return new String();			
		}
		else return objFound;
	}


	public void refresh()
	{
		try
		{
			List itemContent=jobDAO.getJobItems(quoteNum);
			// all rows
			dataVector=new Vector();
			Iterator rows=itemContent.iterator();
			while (rows.hasNext())
			{
				JobItem jobItem=(JobItem)rows.next();
				Item item =null;
				try {
					item = jobDAO.getItem(jobItem.getItemNum());
				}
				catch (DataAccessException ex) {
					System.err.println("Couldn't fill in item table: "+ex.getMessage());
				}			
				Vector row=new Vector();
				row.add(jobItem.getItemNum());
				Integer qtyInt = new Integer(jobItem.getQtyString());
				row.add(qtyInt);
				if (item!=null) {					
					Double priceDbl = new Double(jobItem.getPrice());
					row.add(priceDbl);
					row.add(jobItem.getItemDesc());
					Double costDbl = new Double(item.getCost());
					row.add(costDbl);
					double totPrice=qtyInt.intValue()*priceDbl.doubleValue();
					row.add(new Double(rounder(totPrice)));
					double totCost=qtyInt.intValue()*costDbl.doubleValue();
					row.add(new Double(rounder(totCost)));
					double margin = (totPrice -totCost)/totPrice*100;
					row.add(new Double(rounder(margin)));					
				}
				else {
					row.add(new Double(0));
					row.add(new String());					
					row.add(new Double(0));
					row.add(new Double(0));
					row.add(new Double(0));
					row.add(new Double(0));					
				}
				dataVector.add(row);
			}
		}
		catch (DataAccessException ex)
		{
			ex.printStackTrace(System.err);
		}
	}

	public boolean isCellEditable(int rowIndex,
                              int columnIndex) {
		if ((columnIndex==ITEM_NUM) || (columnIndex==ITEM_QTY) || (columnIndex==ITEM_PRICE) || (columnIndex==ITEM_DESC)) {
			return true;
		}
		return false;		
	}
	
	private double rounder(double entry) {
		return (double)Math.round(entry*100)/100;
	}

    public static void main(String[] args) {
        //ContainerEntryTable allManifestsTable1 = new ContainerEntryTable();
    }
}